import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class JSpUtil {
  JSpUtil._internal();

  factory JSpUtil() => _instance;

  static final JSpUtil _instance = JSpUtil._internal();

  static late SharedPreferences _preferences;

  static Future<JSpUtil> getInstance() async {
    _preferences = await SharedPreferences.getInstance();
    return _instance;
  }

  /// 通用设置持久化数据
  static setLocalStorage<T>(String key, T value) {
    String type = value.runtimeType.toString();

    switch (type) {
      case "String":
        _preferences.setString(key, value as String);
        break;
      case "int":
        _preferences.setInt(key, value as int);
        break;
      case "bool":
        _preferences.setBool(key, value as bool);
        break;
      case "double":
        _preferences.setDouble(key, value as double);
        break;
      case "List<String>":
        _preferences.setStringList(key, value as List<String>);
        break;
      case "_InternalLinkedHashMap<String, String>":
        // setMap(key, value as Map);
        _preferences.setString(key, json.encode(value));

        break;
    }
  }

  /// 获取持久化数据
  static dynamic getLocalStorage<T>(String key) {
    dynamic value = _preferences.get(key);
    if (value.runtimeType.toString() == "String") {
      if (_isJson(value)) {
        return json.decode(value);
      }
    }
    return value;
  }

  /// 获取持久化数据中所有存入的key
  static Set<String> getKeys() {
    return _preferences.getKeys();
  }

  /// 获取持久化数据中是否包含某个key
  static bool containsKey(String key) {
    return _preferences.containsKey(key);
  }

  /// 删除持久化数据中某个key
  static Future<bool> remove(String key) async {
    return await _preferences.remove(key);
  }

  /// 清除所有持久化数据
  static Future<bool> clear() async {
    return await _preferences.clear();
  }

  /// 重新加载所有数据,仅重载运行时
  static Future<void> reload() async {
    return await _preferences.reload();
  }

  /// 判断是否是json字符串
  static _isJson(String value) {
    try {
      JsonDecoder().convert(value);
      return true;
    } catch (e) {
      return false;
    }
  }
}
